package com.frxuexi.shop.viewmodel

import com.frxuexi.base.db.ShopDao
import com.frxuexi.base.http.ShopApiService
import com.frxuexi.base.mvi.BaseViewModel
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.shop.intent.ShopIntent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

@HiltViewModel
class ShopViewModel @Inject constructor(val apiService: ShopApiService,val shopDao: ShopDao):BaseViewModel<ShopIntent>() {
    override fun handleIntent(it: ShopIntent) {
        when(it){
            is ShopIntent.getShops ->httpRequest(apiService.getShops(it.type))
            is ShopIntent.getHomeData->httpRequest(apiService.getHomeData(),RequestType.HOME)
            is ShopIntent.getShopDetail->httpRequest(apiService.getShopDetail(it.id))
            is ShopIntent.insertShop->roomRequest(flow { emit(shopDao.insertShop(it.shopLoveEntity)) },RequestType.ADD)
            is ShopIntent.deleteShop->roomRequest(flow { emit(shopDao.deleteShop(it.shopLoveEntity)) },RequestType.DELETE)
            is ShopIntent.selectShopById->roomRequest(flow { emit(shopDao.selectShopById(it.id)) },RequestType.ITEM)
            is ShopIntent.selectShops->roomRequest(flow { emit(shopDao.selectShops()) })
            is ShopIntent.getComments->httpRequest(apiService.getCommemts(it.id,it.page,it.type),RequestType.COMMENTS)
            is ShopIntent.addCart->httpRequest(apiService.addCart(toBody(it.map)),RequestType.ADDCART)
        }
    }
}